#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <dlfcn.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>

// IPMI 目标地址和端口
#define IPMI_TARGET_IP "127.0.0.1"
#define IPMI_TARGET_PORT 623

#define CHUNK_SIZE 60 // 每个 IPMI 包的文件内容块大小

// CRC16 算法
unsigned short crc16(const unsigned char *data, size_t length) {
    unsigned short crc = 0xFFFF;
    for (size_t i = 0; i < length; i++) {
        crc ^= data[i];
        for (int j = 0; j < 8; j++) {
            if (crc & 1)
                crc = (crc >> 1) ^ 0xA001;
            else
                crc >>= 1;
        }
    }
    return crc;
}

// 数据发送函数
void send_ipmi_packet(const char *packet, size_t size) {
    struct sockaddr_in server_addr;
    int sock = socket(AF_INET, SOCK_DGRAM, 0);
    if (sock < 0) {
        perror("Socket creation failed");
        exit(EXIT_FAILURE);
    }

    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(IPMI_TARGET_PORT);
    inet_pton(AF_INET, IPMI_TARGET_IP, &server_addr.sin_addr);

    // 发送数据
    if (sendto(sock, packet, size, 0, (struct sockaddr *)&server_addr, sizeof(server_addr)) < 0) {
        perror("Failed to send packet");
    }
    close(sock);
}

// 在 main 函数之前执行
void __attribute__((constructor)) before_main() {
    printf("TSB Agent: Intercepting before main.\n");

    // 获取当前可执行文件路径
    char exe_path[1024];
    ssize_t len = readlink("/proc/self/exe", exe_path, sizeof(exe_path) - 1);
    if (len < 0) {
        perror("Failed to get executable path");
        return;
    }
    exe_path[len] = '\0';

    // 打开可执行文件
    int fd = open(exe_path, O_RDONLY);
    if (fd < 0) {
        perror("Failed to open executable");
        return;
    }

    // 获取文件大小
    struct stat st;
    if (fstat(fd, &st) < 0) {
        perror("Failed to get file size");
        close(fd);
        return;
    }
    size_t file_size = st.st_size;

    // 计算总包数量
    size_t total_packets = (file_size + CHUNK_SIZE - 1) / CHUNK_SIZE;
    printf("TSB Agent: Total packets to send: %zu\n", total_packets);

    // 分块读取并发送
    unsigned char buffer[CHUNK_SIZE];
    unsigned char ipmi_packet[64]; // IPMI 包大小
    size_t bytes_read, total_sent = 0;

    for (size_t packet_index = 0; packet_index < total_packets; packet_index++) {
        memset(buffer, 0, sizeof(buffer));
        memset(ipmi_packet, 0, sizeof(ipmi_packet));

        // 读取文件分块
        bytes_read = read(fd, buffer, CHUNK_SIZE);
        if (bytes_read < 0) {
            perror("Failed to read executable");
            break;
        }

        // 填充 IPMI 包头
        ipmi_packet[0] = (unsigned char)total_packets;      // 总包数量
        ipmi_packet[1] = (unsigned char)(packet_index + 1); // 当前包索引

        // 计算 CRC16
        unsigned short crc = crc16(buffer, bytes_read);
        ipmi_packet[2] = (unsigned char)(crc & 0xFF);       // CRC16 低字节
        ipmi_packet[3] = (unsigned char)((crc >> 8) & 0xFF); // CRC16 高字节

        // 填充文件分块内容
        memcpy(ipmi_packet + 4, buffer, bytes_read);

        // 发送 IPMI 包
        send_ipmi_packet((const char *)ipmi_packet, sizeof(ipmi_packet));
        total_sent += bytes_read;
        printf("TSB Agent: Sent packet %zu/%zu (%zu bytes).\n", packet_index + 1, total_packets, total_sent);
    }

    close(fd);
    printf("TSB Agent: Finished sending executable file.\n");
}

// LD_PRELOAD=./tsb_agent.so ./target_executable